import 'package:flustars/flustars.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:tracker/common/enums/LoginTypeEnum.dart';
import 'package:tracker/startup/config/model/global_config_resp.dart';

part 'global_state_provider.g.dart';
part 'global_state_provider.freezed.dart';

@riverpod
class GlobalState extends _$GlobalState {
  @override
  GlobalStateModel build() {
    // 初始状态
    var model = GlobalStateModel();
    // 读取登录状态
    final isLogin = SpUtil.getBool('isLogin') ?? false;
    // 读取全局配置
    final globalConfig = SpUtil.getObject('globalConfig') == null
        ? GlobalConfigData()
        : GlobalConfigData().fromJson(SpUtil.getObject('globalConfig')!);

    return model.copyWith(
      isLogin: isLogin,
      globalConfig: globalConfig,
    );
  }

  void updateState(GlobalStateModel newState) {
    state = newState;
  }

  // 更新登录类型
  void updateLoginType(LoginTypeEnum newLoginType) {
    state = state.copyWith(loginType: newLoginType);
  }

  // 添加更新全局配置的方法
  void updateGlobalConfig(GlobalConfigData globalConfig) {
    state = state.copyWith(globalConfig: globalConfig);
    SpUtil.putObject('globalConfig', globalConfig);
  }
}

@freezed
class GlobalStateModel with _$GlobalStateModel {
  factory GlobalStateModel({
    // 是否登录
    @Default(false) bool isLogin,

    // 登录类型
    @Default(LoginTypeEnum.device) LoginTypeEnum loginType,
    // 添加全局配置字段
    GlobalConfigData? globalConfig,
    // 在这里添加更多属性
  }) = _GlobalStateModel;
}
